from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic.simple import direct_to_template
from djwatch.models import Server, Check
from djwatch.visualization import get_server_stat, get_times, \
    compose_static_image
from django.core.urlresolvers import reverse
from djwatch.forms import ServerForm
from django.shortcuts import get_object_or_404
from django.conf import settings

plugins_list = []
plugins_dict = {}
for name, mod in getattr(settings, 'PLUGINS', ()):
    plugins_list.append(name)
    mod, func = mod.rsplit('.', 1)
    plugins_dict[name] = getattr(__import__(mod, {}, {}, [func]), func)

@login_required
def index(request):
    return direct_to_template(request, 'index.html', {})

@login_required
def create_server(request):
    form = ServerForm(request.POST or None)
    if form.is_valid():
        server = form.save()
        return HttpResponseRedirect(reverse(server_reports, args=[server.id]))
    return direct_to_template(request, 'create_server.html', {
        'form': form,
    })

@login_required
def server_reports(request, server_id):
    server = get_object_or_404(Server, id=server_id)
    try:
        last_check = Check.objects.filter(server=server).order_by('-datetime')[0]
    except IndexError:
        last_check = None
    return direct_to_template(request, 'server_reports.html', {
        'server': server,
        'plugins': plugins_list,
        'last_check': last_check,
    })

@login_required
def server_settings(request, server_id):
    server = get_object_or_404(Server, id=server_id)
    form = ServerForm(request.POST or None, instance=server)
    if request.POST and form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse(server_reports, args=[server.id]))
    return direct_to_template(request, 'server_settings.html', {
        'server': server,
        'form': form,
    })

def graph_image(request, w, h, server_id, plugin):
    times = get_times(3)
    stat = get_server_stat(times, server_id)
    graph_data = plugins_dict[plugin](stat)
    image = compose_static_image(graph_data, times, size=(w, h))
    return HttpResponse(image, content_type='image/png')
